//
//  MessageViewController.m
//  tangshantongjiAPPFull
//
//  Created by yuntai on 2018/4/27.
//  Copyright © 2018年 yuntai. All rights reserved.
//

#import "MessageViewController.h"
#import "ConnectListCell.h"
#import "ContactChatListViewController.h"
#import "XiaoJiaNotiListCell.h"
#import "CommonModel.h"
#import "NotiMessageListViewController.h"
#import "NotiDetailViewController.h"
#import "EPublicMacros.h"

@interface MessageViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *xiaoJiaArray;
@property (nonatomic, strong) NSMutableArray *contectArray;

@property (nonatomic, copy) NSString *notitime;
@property (nonatomic, copy) NSString *noticontent;
@property (nonatomic, strong) NSIndexPath *indexPath;

@end

@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.xiaoJiaArray = [NSMutableArray array];
    self.contectArray = [NSMutableArray array];
    self.tableview.backgroundColor = kBGColor;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateMessageNotiMethod:) name:kXMPPRecvChatMsgNotifaction object:nil];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:kXMPPRecvChatMsgNotifaction object:nil];
}


- (void)updateMessageNotiMethod:(NSNotification *)noti{
    
    self.contectArray =  [[IWxChatMgrChat sharedInstance]getMyAllConversation];
    [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[[[[self tabBarController]tabBar]items]objectAtIndex:1]setBadgeValue:nil];
    // Dispose of any resources that can be recreated.
    /**获取最近联系人*/
    self.contectArray =  [[IWxChatMgrChat sharedInstance]getMyAllConversation];
    [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
    /**获取系统通知*/
    [self getSystemNoti];
    /**获取销价通知*/
    [self getXiaoJiaNoti];
}
-(void)viewDidLayoutSubviews
{
    if ([self.tableview respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableview setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([self.tableview respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableview setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}
#pragma mark - UITableViewDelegate,UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return 1;
    }else if (section == 1 ){
        return self.xiaoJiaArray.count ;
    }else{
        return self.contectArray.count ;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0 || indexPath.section ==2) {
        static NSString *cellId = @"ConnectListCell";
        ConnectListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"ConnectListCell" owner:nil options:0]lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.section == 0) {
            cell.nameLabel.text = @"通知";
            cell.countLabel.hidden = YES;
            cell.headIV.image = [UIImage imageNamed:@"logo"] ;
            cell.detailLabel.text = self.noticontent?:@"无";
            cell.timelabel.text = self.notitime?:@"";
        }else{
            [cell configcellWithModel:self.contectArray[indexPath.row] index:indexPath];
        }
        return cell;
    }else{
        static NSString *xiaojiacellId = @"XiaoJiaNotiListCell";
        XiaoJiaNotiListCell *cell = [tableView dequeueReusableCellWithIdentifier:xiaojiacellId];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"XiaoJiaNotiListCell" owner:nil options:0]lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        CommonModel *model = self.xiaoJiaArray[indexPath.row];
        cell.titleLabel.text = model.title?:@"";
        cell.detailLabel.text = model.notice_desc?:@"";
        cell.statusLabel.text = model.is_read ? @"已读":@"未读";
        cell.statusLabel.textColor = model.is_read ? kTextDeepDarkColor:kNavigationColor;
        return cell;
    }
    return nil;
   
}

#pragma mark - UITableViewDelegate
/**设置cell高度*/
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==1) {
        return 90;
    }else{
        return 55;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 1) {
        return self.xiaoJiaArray.count ? 10:0;
    }else if(section == 2){
        return self.contectArray.count ? 10:0;
    }else{
        return 10;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 2) {
        
//        ConnectListCell *cell = [tableView cellForRowAtIndexPath:indexPath];

        ChatRecent *model = self.contectArray[indexPath.row];
        
        ContactChatListViewController *vc = [[ContactChatListViewController alloc]init];
        vc.contactMemID = model.ContactId;
        vc.contactMemName  = model.ContactName;
        vc.title = model.ContactName?: @"聊天";
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == 0){
        NotiMessageListViewController *vc = [[NotiMessageListViewController alloc]init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        CommonModel *mdel = self.xiaoJiaArray[indexPath.row];
        self.indexPath = indexPath;
        if (mdel.is_read) {
            NotiDetailViewController *vc = [[NotiDetailViewController alloc]init];
            vc.hidesBottomBarWhenPushed = YES;
            vc.model = mdel;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [self updateMessageStatueWith:self.xiaoJiaArray[indexPath.row]];
        }

    }
    
    
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


- (void)getSystemNoti{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:kTokenID forKey:@"token"];
    [params setValue:@"1" forKey:@"page"];
    
    [NetWork PostNetWorkWithUrl:@"api/notice/getAllNotice.ajax" with:params successBlock:^(NSDictionary *dic) {
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        
        NSArray *temparray = dic[@"data"][@"data"];
        if (temparray.count) {
            NSDictionary *temdic = temparray[0];
            if (temdic) {
                self.notitime = temdic[@"time"]?:@"";
                self.noticontent = temdic[@"notice_desc"]?:@"";
            }
        }
        
        [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        
    } FailureBlock:^(NSString *msg) {
        [self.tableview.mj_header endRefreshing];
        [HUDManager showWarningWithText:msg];
        
    } errorBlock:^(id error) {
        [self.tableview.mj_header endRefreshing];
        
    }];
}

- (void)getXiaoJiaNoti{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:kTokenID forKey:@"token"];
    
    [NetWork PostNetWorkWithUrl:@"api/notice/getNotice.ajax" with:params successBlock:^(NSDictionary *dic) {
        [self.tableview.mj_header endRefreshing];
        
        NSArray *temparray = dic[@"data"][@"data"];
        if (self.currentPage == 1) {
            [self.xiaoJiaArray removeAllObjects];
        }
        
        [self.xiaoJiaArray addObjectsFromArray:[CommonModel mj_objectArrayWithKeyValuesArray:temparray]];
        
        [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
        
    } FailureBlock:^(NSString *msg) {
        [self.tableview.mj_header endRefreshing];
        [HUDManager showWarningWithText:msg];
        
    } errorBlock:^(id error) {
        [self.tableview.mj_header endRefreshing];
    }];
}

- (void)updateMessageStatueWith:(CommonModel *)model{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:kTokenID forKey:@"token"];
    [params setValue:model.modelId forKey:@"id"];
    
    [NetWork PostNetWorkWithUrl:@"api/notice/update.ajax" with:params successBlock:^(NSDictionary *dic) {
        
        CommonModel *model = self.xiaoJiaArray[self.indexPath.row];
        model.is_read = YES;
        [self.tableview reloadRowsAtIndexPaths:@[self.indexPath] withRowAnimation:UITableViewRowAnimationNone];
        NotiDetailViewController *vc = [[NotiDetailViewController alloc]init];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
        
        
    } FailureBlock:^(NSString *msg) {
        [HUDManager showWarningWithText:msg];
        
        
    } errorBlock:^(id error) {
        
    }];
}
@end
